﻿namespace SimpleTPL;

public static class Program
{
    public static void Main()
    {
        // TestSimpleTask();

        var task = TestSimpleTaskAsync();
        
        while (!task.IsCompleted)
        {
            Thread.Sleep(1000);
        }
        
        Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Result={((SimpleTask<int>)task).Result} ");

        Console.WriteLine("Exiting...");
    }

    private static void TestSimpleTask()
    {
        Console.WriteLine("Main thread: " + Thread.CurrentThread.ManagedThreadId);

        // 简单任务
        var task1 = SimpleTask.Run(() => 
        {
            Console.WriteLine("Task 1 running on thread: " + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(500);
        });

        // 带返回值的任务
        var task2 = SimpleTask.Run(() => 
        {
            Console.WriteLine("Task 2 computing on thread: " + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(1000);
            return 42;
        });

        task2.ContinueWith(t => 
        {
            Console.WriteLine($"Got result: {t.Result} on thread: " + Thread.CurrentThread.ManagedThreadId);
        });

        // 使用 Delay
        SimpleTask.Delay(1500).ContinueWith(_ => 
        {
            Console.WriteLine("Delay completed on thread: " + Thread.CurrentThread.ManagedThreadId);
        });

        Console.WriteLine("All tasks started. Press any key to exit...");
    }

    private static SimpleTask TestSimpleTaskAsync()
    {
        Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] TestSimpleTaskAwaiter start");
        
        var task = GetAnswerAsync();
        
        task.ContinueWith(t => 
        {
            if (t._exception != null)
                Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Exception={t._exception.Message} "+ Thread.CurrentThread.ManagedThreadId);
        });

        return task;
    }
    
    static SimpleTask GetAnswerAsync()
    {
        var stateMachine = new AutoGen.GetAnswerAsyncStateMachine();
        var builder = SimpleAsyncMethodBuilder<int>.Create();
        stateMachine.Builder = builder;
        builder.Start(ref stateMachine);
        return builder.Task;
    }
}

